<template>
  <div class="main_spac1 maincl" style="height:100%;">
    <div class="main_white padding10">
      <div class="mainor_form small-top">
        <el-form
          :inline="true"
          :model="form"
          class="demo-form-inline"
          ref="userListFrom"
          label-width="90px"
          id="form"
        >
          <el-form-item label="商品：" prop="name">
            <el-input
              v-model.trim="form.name"
              placeholder="商品名称"
              clearable
              class="wid220"
            ></el-input>
          </el-form-item>
          <el-form-item label="分类：" prop="category_id" class="wid220">
            <el-cascader
              v-model="form.category_id"
              :options="options"
              :props="defaultProps"
              @change="getArticleList"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="状态：" prop="status">
            <el-select
              v-model.trim="form.status"
              placeholder="商品状态"
              class="wid220"
              @change="getArticleList"
            >
              <el-option label="所有" value=""></el-option>
              <el-option
                v-for="(statusList, index) in list.statusList"
                :key="index"
                :label="statusList"
                :value="index + 1"
              ></el-option>
            </el-select>
          </el-form-item>
          <MainFormBtn @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="moredata">
          </MainFormBtn>
          <div class="more el-form-item" @click="more">
            <span>更多</span>
            <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
          </div>
          <div class="clearfix"></div>
          <el-collapse-transition>
            <div v-show="moredata">
              <el-form-item label="品牌：" prop="brand_id">
                <change-brand-input
                  :brandlist="brandlist"
                  ref="changeBrandInput"
                  @clear="
                    () => {
                      this.form.brand_id = '';
                    }
                  "
                  @sendValue="
                    (data) => {
                      this.form.brand_id = data.id;
                    }
                  "
                ></change-brand-input>
              </el-form-item>
              <el-form-item label="编码：" prop="goods_code">
                <el-input
                  v-model.trim="form.goods_code"
                  placeholder="编码"
                  clearable
                  class="wid220"
                ></el-input>
              </el-form-item>
              <el-form-item label="别名：" prop="byname">
                <el-input
                  v-model.trim="form.byname"
                  placeholder="别名"
                  clearable
                  class="wid220"
                ></el-input>
              </el-form-item>

              <el-form-item label="标品：" prop="is_standard">
                <el-select
                  v-model.trim="form.is_standard"
                  placeholder="是否标品"
                  class="wid220"
                  @change="getArticleList"
                >
                  <el-option label="所有" value=""></el-option>
                  <el-option
                    v-for="(standardList, index) in list.standardList"
                    :key="index"
                    :label="standardList"
                    :value="index + 1"
                  ></el-option>
                </el-select>
              </el-form-item>
              <div class="clearfix"></div>
              <el-form-item label="时价：" prop="current_price">
                <el-select
                  v-model.trim="form.current_price"
                  placeholder="时价"
                  class="wid220"
                  @change="getArticleList"
                >
                  <el-option label="所有" value="0"></el-option>
                  <el-option label="是" value="2"></el-option>
                  <el-option label="否" value="1"></el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="推荐" prop="is_recommend">
                <el-select
                  v-model.trim="form.is_recommend"
                  placeholder="今日推荐"
                  class="wid220"
                >
                  <el-option label="所有" value=""></el-option>
                  <el-option
                    v-for="(recommendList, index) in list.recommendList"
                    :key="index"
                    :label="recommendList"
                    :value="index + 1"
                  ></el-option>
                </el-select>
              </el-form-item> -->
              <el-form-item label="标签：" prop="label_ids">
                <el-checkbox-group v-model="form.label_ids">
                  <el-checkbox
                    v-for="(tag, index) in list.tag"
                    :key="index"
                    :label="tag.id"
                    >{{ tag.title }}</el-checkbox
                  >
                </el-checkbox-group>
              </el-form-item>
              <div class="clearfix"></div>
              <el-form-item label=" ">
                <MainFormBtn class="btn-bottom mg-t-0" @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="!moredata">
                </MainFormBtn>
              </el-form-item>
            </div>
          </el-collapse-transition>
        </el-form>
      </div>

      <div class="main-controls-wrap">
        <div class="flex">
          <el-button type="primary" @click="addGoods">新增商品</el-button>
          <div class="main_num mg-r-6">
            <div class="main_num_r box">
              <el-dropdown>
                <el-button type="primary">
                  批量设置<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    ><p @click="batch(1)">批量上架</p></el-dropdown-item
                  >
                  <el-dropdown-item>
                    <p @click="batch(0)">批量下架</p></el-dropdown-item
                  >
                  <el-dropdown-item>
                    <p @click="batchStandard(1)">标品</p>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <p @click="batchStandard(0)">非标品</p>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <p @click="deleteMany">批量删除</p></el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
              <!-- <p @click="batch(1)">
                <el-button>批量上架</el-button>
              </p>
              <p @click="batch(0)">
                <el-button>批量下架</el-button>
              </p>
              <p @click="deleteMany">
                <el-button>批量删除</el-button>
              </p> -->
            </div>
          </div>
          <el-button @click="importDialog" class="mg-r-6">导入</el-button>
          <el-button @click="exportConirm">导出</el-button>
        </div>
      </div>
    
      <div class="main_table" :style="{ height: borderHeight + 'px' }">
        <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list.list.data"
          element-loading-text="加载中"
          fit
          border
          :height="borderHeight"
          highlight-current-row
          :row-class-name="getRowClass"
          @selection-change="handleSelectionChange"
          :header-cell-class-name="this.$verticaline"
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
          @header-dragend="changeTableWidth"
        >
          <el-table-column type="expand" class-name="main_hei">
            <template slot-scope="props">
              <el-table
                :data="props.row.spu"
                class="mainex_ta"
                fit
                :highlight-current-row="false"
              >
                <el-table-column label width="40" align="right" />
                <el-table-column
                  label="SKU规格"
                  prop="spu_name.title"
                  width="200"
                />
                <el-table-column label="单位" prop="spu_unit.title" width="200">
                  <template slot-scope="scope"
                    >{{ scope.row.spu_unit.title
                    }}<span
                      v-if="
                        scope.row.transfer_num && scope.row.spu_transfer_unit
                      "
                    ></span
                  ></template>
                  <!-- 【约{{
                      scope.row.transfer_num
                    }}{{ scope.row.spu_transfer_unit.title }}】 -->
                </el-table-column>
                <!-- <el-table-column label="条码" prop="goods_spu_code" /> -->
                <!-- <el-table-column
                  label="损耗率"
                  prop="attrition_rate"
                  :render-header="renderHeader4"
                /> -->
                <el-table-column label="起订量" prop="minimum" />
                <el-table-column label="互调比" prop="package_num" />
                <el-table-column label="指定库存" prop="designated_inventory" />
                <el-table-column
                  label="售卖状态"
                  prop="status"
                  width="160"
                  class-name="main_hei"
                >
                  <template slot-scope="scope"
                    ><span
                      :class="scope.row.status == 1 ? 'success' : 'unpaid'"
                    >
                      {{ scope.row.status == 1 ? "是" : "否" }}</span
                    ></template
                  >
                </el-table-column>
                <el-table-column label prop width="80" />
              </el-table>
            </template>
          </el-table-column>

          <el-table-column type="selection" align="center" />
          <div v-for="(field, index) in list.field" :key="index">
            <el-table-column
              label="名称"
              prop="name"
              align="center"
              :width="tableWidth[hash+'name']"
              :resizable="true"
              v-if="field == 1"
            >
              <template slot-scope="scope">
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  "
                >
                  <div class="user_cell_cox">
                    <div v-show="scope.row.labels.length > 0">
                      <el-popover
                        placement="bottom-start"
                        width="200"
                        trigger="hover"
                      >
                        <div class="item-label">
                          <span v-for="item in scope.row.labels" :key="item">
                            {{ tags[item] }}
                          </span>
                        </div>

                        <img
                          slot="reference"
                          class="label-pic"
                          src="../../assets/images/10.png"
                        />
                      </el-popover>
                    </div>
                    <div>{{ scope.row.name }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column
              label="别名"
              prop="byname"
              :width="tableWidth[hash + 'byname']"
              v-if="field == 2"
            />
            <el-table-column
              label="图片"
              align="center"
              class-name="main_hei"
              width="120"
              :resizable="true"
              v-if="field == 3"
            >
              <template slot-scope="scope">
                <div class="demo-image__error mainor_im">
                  <el-image
                    fit="fill"
                    :src="scope.row.pic"
                    :preview-src-list="scope.row.pics"
                  >
                    <div slot="error" class="image-slot">
                      <img :src="puzzleImg" />
                    </div>
                  </el-image>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="分类"
              prop="category_name"
              align="center"
              :width="tableWidth[hash + 'category_name'] || 180"
              v-if="field == 4"
            >
              <template slot-scope="scope">{{
                scope.row.category_name
              }}</template>
            </el-table-column>
            <el-table-column
              label="编码"
              align="center"
              prop="goods_code"
              :width="tableWidth[hash + 'goods_code']"
              v-if="field == 5"
            />
            <el-table-column
              label="排序"
              prop="sort"
              :width="tableWidth[hash + 'sort'] || 150"
              :render-header="field == 6 ? renderHeader2 : ''"
              class-name="table-sort"
              v-if="field == 6"
            >
              <template slot-scope="scope">{{ scope.row.sort }}</template>
            </el-table-column>
            <el-table-column
              label="市场价"
              prop="market"
              align="center"
              :width="tableWidth[hash + 'market'] || 120"
              v-if="field == 7"
            />
            <el-table-column
              label="上架状态"
              align="center"
              prop="status"
              :width="tableWidth[hash + 'status']"
              v-if="field == 8"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <span :class="scope.row.status == 1 ? 'success' : 'unpaid'">
                  {{ scope.row.status == 1 ? "上架" : "下架" }}
                </span></template
              >
            </el-table-column>
            <el-table-column
              label="商品ID"
              prop="id"
              :width="tableWidth[hash + 'id']"
              v-if="field == 9"
            >
            </el-table-column>
          </div>
          <el-table-column
            prop="operate"
            :width="tableWidth[hash + 'operate']"
            class-name="main_hei"
          >
            <template slot="header">
              <table-header-setting
                @openHeader="dialogFormVisible = true"
              ></table-header-setting>
            </template>
            <template slot-scope="scope">
              <!-- <router-link :to="'/commodity/list/edit/' + scope.row.id">
                <el-link type="primary">编辑</el-link>
              </router-link> -->
              <el-link type="primary" @click="openEdit(scope.row.id)">编辑</el-link>
              <el-link type="danger" @click="delet(scope.$index, scope.row.id)"
                >删除</el-link
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="main_num boxdq marginTop10">
        <div>
          <div class="main_num_l box">
            <p>
              商品数量：
              <em>{{ list.all }}</em>
            </p>
            <p>
              上架数量：
              <em>{{ list.all1 }}</em>
            </p>
            <p>
              下架数量：
              <em>{{ list.all2 }}</em>
            </p>
            <p>
              回收站：
              <em>{{ list.del }}</em>
            </p>
          </div>
        </div>
        <!-- 分页 -->
        <div class="main_page_r">
          <MainPagination
            :current-page="current.page"
            :page-sizes="[20, 30, 50, 100]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            background
            @size-change="changeLimit"
            @current-change="changePage"
          />
        </div>
      </div>
    </div>

    <el-dialog
      title="表头设置"
      :visible.sync="dialogFormVisible"
      class="main_dialog dialog500"
      @close="type = list.field"
    >
      <div class="set_sort">
        <div class="set_none_show">
          <el-checkbox-group v-model="type">
            <el-checkbox
              v-for="(Header, index) in Header"
              :key="index"
              :label="Header.id"
              :disabled="Header.disabled"
              >{{ Header.name }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
        <div class="set_header_sort">
          <div class="set_sort_ab">
            <draggable chosen-class="chosen" v-model="Header" animation="500">
              <transition-group>
                <li
                  class="set_sort_ab_border"
                  v-for="item in Header"
                  :key="item.id"
                >
                  <div>
                    <span class="el-icon-d-caret"></span>
                    <span>{{ item.name }}</span>
                  </div>
                  <svg-icon icon-class="index_move" />
                </li>
              </transition-group>
            </draggable>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="setupmine" v-repeatClick
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 商品导入 -->
    <el-dialog
      title="商品导入"
      :visible.sync="importbuVisible"
      class="main_dialog dialog840 importbu"
    >
      <div class="dialog_padding20_30">
        <div class="importbu_p">
          <h3>导入说明：</h3>
          <p>1.注意使用红色字体标注的必填字段,不填或错填将导致导入失败。</p>
          <p>2.导入文件仅支持xlsx格式,大小不超过2M ,数据不超过2000行。</p>
          <p>3.导入文件不能包含“合并单元格”，否则无法导入。</p>
          <p>
            4.导入时碰到数据不正确的行，系统会跳过错误的行继续执行未完成的行。
          </p>
        </div>
        <div class="importbu_ul">
          <ul>
            <!-- <li>
            <p>已存在(非)标准库中</p>
            <el-radio-group v-model="import_form.goods_type" :border="true">
              <el-radio :label="1">自动从(非)标准库中导入</el-radio>
              <el-radio :label="2">跳过</el-radio>
            </el-radio-group>
          </li> -->
          </ul>
        </div>
        <div class="importbu_in">
          <h3>数据行区间设置</h3>
          <div class="box">
            <p>
              <span>第一个数据行号：</span
              ><el-input-number
                v-model="import_form.start_line_num"
                controls-position="right"
                :min="2"
              ></el-input-number>
            </p>
            <p>
              <span>最后一行数据行数：</span
              ><el-input
                v-model="import_form.end_line_num"
                placeholder="默认为全部"
                type="number"
              ></el-input>
            </p>
          </div>
        </div>
        <div class="importbu_an box">
          <el-button @click="downTemplate" class="marginRight10"
            >下载模板</el-button
          >
          <el-upload
            class="upload-demo"
            :action="goods_import"
            :on-success="importSuccess"
            :on-error="importerr"
            :show-file-list="false"
            :data="import_params"
            :headers="{
              Authorization: getToken(),
            }"
          >
            <el-button size="small" @click="handleUpload" type="primary"
              >点击上传</el-button
            >
          </el-upload>

          <p v-if="import_file_name ? true : false">
            上传文件名：{{ import_file_name }}
          </p>
        </div>
        <div class="import_process" v-if="percentShow">
          <div class="progress">
            <el-progress
              :text-inside="true"
              :stroke-width="20"
              :percentage="percent"
              color="#19B098"
            ></el-progress>
          </div>
          <div class="notice" v-if="percentShow">
            <div class="importtips">
              <p class="success" v-if="percent == 100">商品导入结束</p>
              <div v-for="(item, index) in reverseSum" :key="index">
                <p v-if="item.type == 2" :key="index" class="fail">
                  {{ item.name }}，导入失败
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="cancelDisabled" @click="importbuVisible = false"
          >取 消</el-button
        >
      </div>
    </el-dialog>
    <commodity-list-drawer ref="listDrawer" @getList="goods_index" @pageReload="pageReload"></commodity-list-drawer>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import ChangeBrandInput from "@/components/ChangeBrandInput/indev.vue";
import { mapGetters } from "vuex";
import {
  goods_index,
  goods_delete,
  goods_batchStatus,
  export_goods_list,
  goods_bulk_delete,
  order_down_tem,
  goods_batchStandard,
} from "@/api/commodity/commodityList";
import { field_getField } from "@/api/sort";
import { field_save, puzzleImg, goods_import } from "@/api/currency";
import { parseTime, exportMethod } from "@/utils/index";
import { apiUrl, objKeySort, Md5, packApi } from "@/utils/public";
import { recursion, category } from "@/utils/index";
import draggable from "vuedraggable";
import commodityListDrawer from './commodityListDrawer.vue';
export default {
  mixins: [mixins],
  computed: {
    ...mapGetters(["avatar"]),
    reverseSum() {
      return this.percent_list;
    },
  },
  components: {
    ChangeBrandInput,
    draggable,
    commodityListDrawer,
  },
  directives: {
    // 聚焦元素
    focus: {
      inserted(el) {
        el.querySelector("input").focus();
      },
    },
  },
  data() {
    return {
      exportMethod,
      goods_import: goods_import,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 搜索
      form: {
        name: "",
        label_ids: [],
        brand_id: null,
        byname: "",
        pid: "",
        category_id: [],
        status: null,
        sort: 0,
        is_standard: null,
        is_recommend: null,
        current_price: "",
        goods_code: "",
      },
      // 更多
      moredata: false,

      // 列表数据
      list: {
        list: {
          data: [],
        },
      },

      tags: {}, //商品标签

      puzzleImg,
      listLoading: false,
      // 全选
      selectArr: [],
      // 表头设置
      dialogFormVisible: false,
      type: [],
      Header: [
        {
          id: 1,
          name: "名称",
          disabled: true,
        },
        {
          id: 2,
          name: "别名",
          disabled: false,
        },
        {
          id: 3,
          name: "图片",
          disabled: true,
        },
        {
          id: 4,
          name: "分类",
          disabled: true,
        },
        {
          id: 5,
          name: "编码",
          disabled: false,
        },
        {
          id: 6,
          name: "排序",
          disabled: false,
        },
        {
          id: 7,
          name: "市场价",
          disabled: true,
        },
        {
          id: 8,
          name: "状态",
          disabled: true,
        },
        {
          id: 9,
          name: "商品ID",
          disabled: false,
        },
      ],
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true,
      },

      // 商品导入
      importbuVisible: false,
      import_form: {
        user_type: 1,
        goods_type: 1,
        start_line_num: 2,
        end_line_num: "",
      },
      import_file_name: "",
      import_params: {
        string: "",
      },
      percent_gs: 0,
      percent: 0,
      percentShow: false,
      percent_list: [],
      importArrLength: 1,
      cancelDisabled: false,
      brandlist: [],

      intervelStatus: false,
      timeOut: null,
    };
  },
  // 刷新
  inject: ["reload"],
  mounted() {
    this.sort_data();
    window.Echo.channel("bacthImportGoods." + this.avatar.company_id).listen(
      "BacthImportGoodsEvent",
      (e) => {
        console.log(e);
        this.cancelDisabled = true;
        this.importArrLength = e.notice.count;
        this.percentShow = true;
        if (e.notice.code == 0) {
          this.percent_list.push({
            num: this.percent,
            type: 1,
            name: e.notice.msg,
          });
        } else if (e.notice.code == 100) {
          this.percent_list.push({
            num: this.percent,
            type: 2,
            name: e.notice.msg,
          });
        }
        this.percent_gs = parseInt(this.percent_gs) + 1;
        if ((this.percent_gs / this.importArrLength) * 100 >= 100) {
          this.percent = 100;
          this.cancelDisabled = false;
          return;
        }
        this.percent =
          this.percent_gs / this.importArrLength
            ? parseInt((this.percent_gs / this.importArrLength) * 100)
            : 0;

        if (this.percent >= 97 && this.percent < 100) {
          this.timeOut = null;
          if (!this.intervelStatus) {
            this.timeOut = setTimeout(() => {
              this.intervelStatus = true;
              this.percent = 100;
            }, 3000);
          }
        }
        if (this.percent == 100) this.intervelStatus = true;
      }
    );
  },
  methods: {
    getSearchFor() {
      this.getArticleList();
    },
    startGetting() {
      this.getArticleList();
    },
    //排序
    sort_data() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { type: 1 }
      );
      field_getField(data).then((res) => {
        let arry = JSON.parse(res.data.info.sort);
        if (arry || arry.length) {
          this.Header.sort((a, b) => {
            return arry.indexOf(a.id) - arry.indexOf(b.id);
          });
        }
      });
    },
    // 批量上架、下架
    batch(type) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { status: type })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { ids: JSON.stringify(this.selectArr), status: type }
      );
      if (this.selectArr.length != 0) {
        goods_batchStatus(data).then((res) => {
          if (res.errcode == 0) {
            this.$message({
              message: "批量处理成功",
              type: "success",
            });
            this.$refs.multipleTable.clearSelection();
            this.goods_index();
          } else {
            this.$message.error(res.errmsg);
          }
        });
      } else {
        this.$message.error("请勾选商品");
      }
    },
    // 批量删除
    deleteMany() {
      if (this.selectArr.length == 0) {
        this.$message.warning("请勾选需要删除的商品");
        return;
      }
      let idarr = [];
      if (this.selectArr.length > 0) {
        this.selectArr.forEach((item) => {
          idarr.push(item.id);
        });
      }

      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { ids: JSON.stringify(idarr) }
      );
      let str = `您确定批量删除${idarr.length}个商品吗？`;
      this.$confirm(str, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        goods_bulk_delete(data).then((res) => {
          if (res.errcode == 0) {
            this.$message.success("删除成功");
            this.goods_index();
          }
        });
      });
    },
    // 新增商品
    addGoods(){
      this.$refs.listDrawer.open()
    },
    // 编辑商品
    openEdit(id){
      this.$refs.listDrawer.open(id)
    },
    // 批量标品、非标品
    batchStandard(type) {
      if (this.selectArr.length == 0) {
        this.$message.warning("请勾选需要操作的商品");
        return;
      }
      let idarr = [];
      if (this.selectArr.length > 0) {
        this.selectArr.forEach((item) => {
          idarr.push(item.id);
        });
      }
      let data = {
        ids: JSON.stringify(this.selectArr),
        is_standard: type,
      };
      goods_batchStandard(data).then((res) => {
        if (res.errcode == 0) {
          this.$message.success("批量设置成功");
          this.goods_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 导出询问confirm
    exportConirm() {
      let length = this.selectArr.length;
      if (length == 0) {
        let str = `您尚未勾选需要导出的商品，则默认导出全部`;
        this.$confirm(str, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",

          type: "warning",
        })
          .then(() => {
            this.exportb();
          })
          .catch(() => {});
      } else if (length > 0) {
        this.exportb();
      }
    },
    // 下载模板
    downTemplate() {
      let form = {
        user_type: this.import_form.user_type,
        goods_type: this.import_form.goods_type,
      };
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        form
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      order_down_tem(data).then((res) => {
        this.exportMethod(res, "商品导入模板", notify);
      });
    },
    // 导入
    importDialog() {
      this.import_file_name = "";
      this.percent_gs = 0;
      this.percent = 0;
      this.percentShow = false;
      this.percent_list = [];
      this.importArrLength = 1;
      this.cancelDisabled = false;
      this.importbuVisible = true;
    },
    importerr(err, file, fileList) {
      this.$message.error("上传失败");
    },
    importSuccess(response, file, fileList) {
      if (response.errcode != 0) {
        this.$message.error(response.errmsg);
        return;
      }
      this.import_file_name = file.name;
    },
    handleUpload() {
      this.import_params.string =
        this.import_form.start_line_num + "," + this.import_form.end_line_num;
    },
    // 导出
    exportb() {
      let idarr = [];
      if (this.selectArr.length > 0) {
        this.selectArr.forEach((item) => {
          idarr.push(item.id);
        });
      }

      let ids = idarr.join("-");
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { ids: ids })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { ids: ids }
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_goods_list(data)
        .then((res) => {
          this.exportMethod(res, "商品列表", notify);
        })
        .catch(() => {
          this.$message.error("导出失败");
        });
    },
    // 监听全选
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push({ id: item.id });
      });
    },
    // 判断表格是否有子项，无子项不显示展开按钮
    getRowClass(row) {
      if (row.row.spu) {
        if (row.row.spu.length === 0) {
          return "row-expand-cover";
        }
      }
    },
    // 排序？注释
    renderHeader2(h, { column, $index }) {
      // 这里在最外层插入一个div标签
      return h(
        "div",
        {
          class: "boxnr",
        },
        [
          // h即为cerateElement的简写
          // 在div里面插入span
          h(
            "div",
            {
              class: "maincl_px",
              style: "margin-right: 3px;margin-top:3px;",
            },
            [
              h("i", {
                style: "",
                class:
                  this.form.sort != 1
                    ? "el-icon-arrow-up header"
                    : "el-icon-arrow-up header on",
                on: {
                  click: () => {
                    this.sort(1);
                    // console.log(`${column.label}   ${$index}`);
                  },
                },
              }),
              h("i", {
                style: "top:-2px;",
                class:
                  this.form.sort != 0
                    ? "el-icon-arrow-down header"
                    : "el-icon-arrow-down header on",
                on: {
                  click: () => {
                    this.sort(2);
                    // console.log(`${column.label}   ${$index}`);
                  },
                },
              }),
            ]
          ),
          h("span", {
            // 表示内容
            domProps: {
              innerHTML: column.label,
            },
            on: {
              click: () => {
                console.log(`${column.label}   ${$index}`);
              },
            },
          }),
          h(
            "el-tooltip",
            {
              // 表示属性
              attrs: {
                effect: "dark",
                content:
                  "控制在移动端的展示排序，规则为倒序，即数值越大越靠前！",
                placement: "top",
              },
            },
            [
              h("i", {
                style: "margin-left: 5px;margin-top:-1px;",
                class: "el-icon-question table-msg",
              }),
            ]
          ),
        ]
      );
    },
    // 排序
    sort(id) {
      let header = document.getElementsByClassName("header");
      for (let i = 0; i < header.length; i++) {
        if (header[i].className.indexOf("on") > -1) {
          header[i].classList.remove("on");
        }
      }
      header[id - 1].classList.add("on");
      this.form.sort = id;
      this.goods_index();
    },
    // 损耗率？注释
    renderHeader4(h, { column, $index }) {
      // 这里在最外层插入一个div标签
      return h("div", [
        // h即为cerateElement的简写
        // 在div里面插入span
        h("span", {
          // 表示内容
          domProps: {
            innerHTML: column.label,
          },
          on: {
            click: () => {
              console.log(`${column.label}   ${$index}`);
            },
          },
        }),
        h(
          "el-tooltip",
          {
            // 表示属性
            attrs: {
              effect: "dark",
              content: "未审核的商户，不能登录！",
              placement: "top",
            },
          },
          [
            h("i", {
              style: "margin-left: 5px;margin-top:-1px;",
              class: "el-icon-question table-msg",
            }),
          ]
        ),
      ]);
    },
    //重置
    reset() {
      this.$refs["userListFrom"].resetFields();
      if (this.moredata) {
        this.$refs["changeBrandInput"].brand = "";
      }
      this.goods_index();
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.goods_index();
    },
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.goods_index();
    },
    changePage(page) {
      this.current.page = page;
      this.goods_index();
    },
    // 设置确认
    setupmine(val) {
      let arry = [];
      let arrys = [];
      this.Header.map((e) => {
        arrys.push(e.id);
        this.type.map((p) => {
          if (e.id == p) {
            arry.push(e.id);
            return;
          }
        });
      });
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { type: 1 })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { type: 1, fields: JSON.stringify(arry), sort: JSON.stringify(arrys) }
        // [1,2,3,4,5,6,7,8]
      );
      field_save(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "设置成功",
            type: "success",
          });
          this.reload();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 删除
    delet(index, id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: id, type: 1 })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id, type: 1 }
      );
      this.$confirm("是否删除商品?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          goods_delete(data).then((res) => {
            if (res.errcode == 0) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.list.list.data.splice(index, 1);
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {});
    },
    // 列表
    goods_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      goods_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          let tags = {};
          let labels_ids = [];
          res.data.tag.map((e) => {
            tags[e.id] = e.title;
          });

          this.tags = tags;
          labels_ids = Object.keys(this.tags);
          this.options = recursion(res.data.categoryList, true);

          var category = res.data.category;

          res.data.list.data.map((e) => {
            if (e.images.length != 0) {
              e.images.map((a) => {
                a.path = this.avatar.domain + "/" + a.path;
                if (a.main == 1) {
                  e.pic = a.path;
                }
              });
              e.pics = e.images.map((s) => s.path);
            } else {
              e.pic = "";
              e.pics = [];
            }
            e.market = [];
            e.freight = false;

            e.spu.map((p) => {
              e.market.push(p.market_price);
            });

            e.market =
              e.market.length > 1
                ? this.$toFixed(Math.min(...e.market)) +
                  "~" +
                  this.$toFixed(Math.max(...e.market))
                : e.market[0];

            e.labels = [];
            if (e && e.label_ids) {
              e.labels = e.label_ids.split(",");
            }

            // 筛选--开始
            let arr2 = [];
            labels_ids.filter((item) => {
              e.labels.includes(item) && arr2.push(item);
            });
            e.labels = arr2;
            // 结束

            e.category_name = "";
            let title = [];

            if (category[e.pid]) {
              title.push(category[e.pid].title);
              if (
                category[e.pid].selfNext &&
                category[e.pid].selfNext[e.category_id]
              ) {
                title.push(category[e.pid].selfNext[e.category_id].title);
              }
            }
            e.category_name = title.join("|");
          });

          res.data.brand.map((c) => {
            c.value = c.title;
          });

          this.brandlist = res.data.brand;
          this.type = res.data.field;
          this.list = res.data;

          this.totalCount = res.data.list.total;

          // 在数据更新后执行
          this.$nextTick(() => {
            // myTable是表格的ref属性值
            if (this.$refs.multipleTable && this.$refs.multipleTable.doLayout) {
              this.$refs.multipleTable.doLayout();
            }
          });
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.label_ids = JSON.stringify(form.label_ids);
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);
      return form;
    },
    // 刷新
    pageReload(){
      // location.reload();
      this.goods_index()
    },
  },
  activated() {
    this.$nextTick(()=>{
      this.getNumerical(200);
    })
    // 列表
    this.goods_index();
  },
  created() {},
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.mg-t-0 {
  margin-top: 0 !important;
}
/deep/.main_table .el-table .cell{
  padding-left: 12px;
}
.mainor_form form {
  width: 100%;
}
.maincl {
  .main_table /deep/.el-table--small td {
    padding: 10px 0;
  }
  .main_table /deep/.el-table--small th {
    padding: 10px 0;
  }

  /deep/.el-table {
    tr {
      // &:hover {
      //   background: rgba($color: #03a98e, $alpha: 0.1) !important;
      // }
      // &.hover-row > td {
      //   background: rgba($color: #03a98e, $alpha: 0.1) !important;
      // }
      // .current-row > td {
      //   background: rgba($color: #03a98e, $alpha: 0.1) !important;
      // }
    }
  }
  // /deep/.el-table .el-table__body tr:hover {
  //   background: rgba($color: #03a98e, $alpha: 0.1) !important;
  // }

  // /deep/.el-table .el-table__body tr:hover > td {
  //   background: rgba($color: #03a98e, $alpha: 0.1) !important;
  // }
  /deep/.el-table tr.expanded + tr {
    background: #fafafa !important;
  }
  /deep/.el-table tr.expanded + tr > td {
    background: #fafafa !important;
  }
  /deep/.el-table tr.expanded + tr .mainex_ta {
    background: #fafafa !important;
  }
  /deep/.el-table tr.expanded + tr .mainex_ta th,
  /deep/.el-table tr.expanded + tr .mainex_ta tr {
    background: #fafafa !important;
  }
  /deep/.el-table tr.expanded + tr:hover {
    background: #fafafa !important;
  }
  /deep/.el-table tr.expanded + tr:hover > td {
    background: #fafafa !important;
  }
  /deep/.el-table tr.expanded + tr .el-table tr:hover {
    background: #fafafa !important;
  }
  /deep/.el-table tr.expanded + tr .el-table tr:hover > td {
    background: #fafafa !important;
  }
  /deep/ .table-sort {
    .cell {
      display: flex;
      justify-content: center;
    }
  }
}

// 支付状态
.success {
  color: $green;
}
.unpaid {
  color: $colour_red;
}
// 订单状态
.order0 {
  color: $order_color1;
}
.order1 {
  color: $order_color2;
}
.order2 {
  color: $order_color4;
}
.order3 {
  color: $order_color4;
}

// 导入商品
// 导入进度条
.import_process {
  width: 100%;
}

.progress {
  padding: 15px 40px 15px 0;
}
.import_process {
  margin-top: 15px;
  .notice {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    padding-right: 40px;
    .importtips {
      overflow-y: auto;
      width: 100%;
      height: 84px;
      height: 84px;
      background: #ffffff;
      border: 1px solid #d8d8d8;
      padding: 10px 15px;
      box-sizing: border-box;
      .fail {
        color: #ff5a5a;
        line-height: 1.4;
        font-size: 12px;
      }
      .success {
        color: #19b098;
        line-height: 1.4;
        font-size: 12px;
      }
    }
  }
}

.user_cell_cox {
  display: flex;
  align-items: center;
}
.label-pic {
  width: 16px;
  height: 20px;
  margin-right: 6px;
  margin-top: 2px;
}
.item-label {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.item-label span {
  height: auto;
  padding: 4px 10px;
  border: 1px solid #e6a23c;
  color: #e6a23c;
  margin-bottom: 5px;
  border-radius: 3px;
  margin-right: 10px;
}
/deep/.el-dialog__body {
  padding: 0;
}
/deep/ .el-form-item--small.el-form-item {
  margin-bottom: 10px !important;
}

.boxd {
  position: absolute;
  top: 50px;
  right: 0;
}

/deep/.el-table__body tr.current-row > td.el-table__cell,
.el-table__body tr.selection-row > td.el-table__cell {
  background: none;
}
.demo-image__error {
  margin: 0 auto;
}
</style>
